package cn.wolfcode.wolf2w.redis.service.impl;


import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    //key value都是字符串类型
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {
        //Redis操作规范:考虑key的设计
        //唯一性 可读性 有效性 灵活性

        //String key = "verify_code:" + phone;
        //String key1 = Consts.VERIFY_CODE +":"+phone;
        String key = RedisKeys.VERIFY_CODE.join(phone);
        //参数1:key 参数2:value 参数3:时间 参数4:时间单位
        template.opsForValue().set(key,code,RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        return template.opsForValue().get(key);
    }

    @Override
    public String setToken(UserInfo user) {
        //1:创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisKeys.USER_LOGIN.join(token);
        String value = JSON.toJSONString(user);
        //2:设置redis
        //返回json数据格式
        template.opsForValue().set(key, JSON.toJSONString(user),
                RedisKeys.USER_LOGIN.getTime(),TimeUnit.SECONDS);

        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        //从token中拿出user对象
        if(!StringUtils.hasLength(token)){
            return null;
        }
        String key = RedisKeys.USER_LOGIN.join(token);
        //判断有无该key
        if(template.hasKey(key)){
            String userStr = template.opsForValue().get(key);
            if(StringUtils.hasLength(userStr)){
                //转换类型
                UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);
                //重置token时间
                template.expire(key,RedisKeys.USER_LOGIN.getTime(),TimeUnit.SECONDS );
                return  userInfo;
            }
        }
        return null;
    }
}

